﻿using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using PDFLibNet;

namespace MultiThumbnail.Converters
{
    [Extension("PDF")]
    class PdfThumbConverter:ThumbConverter
    {
        public override bool CreateMiniature(Stream fileStream, string resultPath)
        {
            using (var wrapper = new PDFWrapper())
            {
                wrapper.LoadPDF(fileStream);
                if (ThumbnailGenerator.ExportAllPages)
                {
                    for (var i = 1; i <= wrapper.PageCount; i++)
                    {
                        var path = Path.Combine(Path.GetDirectoryName(resultPath), Path.GetFileNameWithoutExtension(resultPath) + i.ToString("00", CultureInfo.InvariantCulture) + Path.GetExtension(resultPath));
                        ExportTo(wrapper, path, i);
                    }
                }
                else ExportTo(wrapper, resultPath, 1);
                
            }
            return true;
        }

        private void ExportTo(PDFWrapper wrapper, string resultPath, int pageNumber)
        {
            var tmpPath = Path.GetTempFileName();
            wrapper.ExportJpg(tmpPath, pageNumber, pageNumber, 150, 80, -1);
            if (!ImageFormat.Jpeg.Equals(ConverterSettings.ImageFormat))
            {
                //var tmpPath = Path.GetTempFileName();
                //wrapper.ExportJpg(tmpPath, 1, 1, 150, 80, -1);
                ConverterSettings.ConvertImageResult(tmpPath, resultPath);
            }
            else
            {
                if (File.Exists(resultPath))
                    File.Delete(resultPath);
                File.Copy(tmpPath, resultPath);
                //wrapper.ExportJpg(resultPath, 1, 1, 150, 80, -1);
            }            
        }
    }
}
